import { defineStore } from 'pinia'
import { topCategory } from '@/api/constants'
import { CateGoryList } from '@/types/category'
import { findAllCategory } from '@/api/category'

// 分类列表
const categoryStore = defineStore({
  id: 'categoryStore',
  state: () => ({
    list: topCategory.map(item => ({ name: item })) as CateGoryList[]
  }),

  actions: {
    setList(categoryList: CateGoryList[]) {
      this.list = categoryList
    },
    // 修改当前一级分类下的open数据为true
    show(item: CateGoryList) {
      const category = this.list.find(category => category.id === item.id)
      category.open = true
    },
    // 修改当前一级分类下的open数据为false
    hide(item: CateGoryList) {
      const category = this.list.find(category => category.id === item.id)
      category.open = false
    },
    getList() {
      return new Promise<CateGoryList[]>((resolve, reject) => {
        findAllCategory()
          .then(res => {
            res.data.result.forEach((item: { open: boolean }) => {
              item.open = false
            })
            this.setList(res.data.result)
            resolve(res.data.result)
          })
          .catch(err => {
            reject(err)
          })
      })
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'category',
        storage: localStorage,
        paths: ['list']
      }
    ]
  }
})

export default categoryStore
